package com.gf.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gf.bean.User;
import com.gf.service.impl.UserServiceImpl;
import com.gf.utils.Const;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
* 处理用户注册servlet
* */


@WebServlet(name = "suser",urlPatterns = "/signuser")
public class SignUserServlet extends HttpServlet {
    static UserServiceImpl usermapper ;
    static  {
        usermapper=new UserServiceImpl();

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");

        PrintWriter out = response.getWriter();
      try {
          String user_name=request.getParameter("signusername");
          String user_password=request.getParameter("signpassword");
          //获取传递过来的账号密码参数
          User user = usermapper.selectByUsername(user_name);
          //验证账号在数据库中有无存在
          JSONObject backjson = new JSONObject();
          //如果判断出用户为null直接返回结果
          if (user!=null){
                //如果账户存在就返回330错误并且携带相应的错误信息
              response.setStatus(330);
              backjson.put("state", 330);
              backjson.put("message", Const.SIGN_LOGINACCT_ERROR);

          }else {
              User signuser=new User();
              //如果不存在就是可以注册就可以先创建user对象
              signuser.setUser_name(user_name);
              //将账户和密码赋值到user中
              signuser.setUser_password(user_password);
              signuser.setDelivery_number(0);
              //默认送件数为0
              usermapper.insert(signuser);
              //将封装好数据的user对象插入
              response.setStatus(200);
              //再设置响应成功的状态码和响应信息
              backjson.put("state", 200);
              backjson.put("message", Const.SIGN_SUCCESS);
          }
          //通过writer对象进行输出正确格式json对象
          out.println(JSON.toJSONString(backjson));
      }catch (Exception e){
          System.out.println(e);
      }
      //刷新writer对象
      //关闭writer对象
        out.flush();
        out.close();



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {




    }
}
